﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WebHttpApi.WebHttpApi.Core;
using WebHttpApi.WebHttpApi.HttpApi;

namespace WebHttpApi
{
    /// <summary>
    /// TYGetMeterHistoryData 的摘要说明：第三方数据请求接口（数据查询）
    /// </summary>
    public class TYGetMeterHistoryData : IHttpHandler
    {
        string str_result = "";

        public void ProcessRequest(HttpContext context)
        {
            //application/json方式：即为JSON数据，不需要检查
            context.Response.ContentType = "application/json";

            //请求主体：JSON格式字符串
            string UserName = "";
            string PassWord = "";
            string MeterId = "";
            string BeginTime = "";
            string EndTime = "";
            string Departmentid = "";

            Stream postData = context.Request.InputStream;
            if (postData.Length != 0)
            {
                StreamReader sRead = new StreamReader(postData);
                string postContent = sRead.ReadToEnd();

                sRead.Close();
                JObject json_post = (JObject)JsonConvert.DeserializeObject(postContent);

                UserName = json_post["UserName"].ToString();
                PassWord = json_post["PassWord"].ToString();
                MeterId = json_post["MeterId"].ToString();

                BeginTime = json_post["BeginTime"].ToString();
                BeginTime = Convert.ToDateTime(BeginTime).ToString("yyyy-MM-dd HH:mm:ss");
                EndTime = json_post["EndTime"].ToString();
                EndTime = Convert.ToDateTime(EndTime).ToString("yyyy-MM-dd HH:mm:ss");

                if (SelectIn(UserName, PassWord, MeterId, BeginTime, EndTime))
                {
                    if (DateDiff(BeginTime, EndTime) < 31)
                    {
                        Departmentid = TYMeter.DepartmentId(UserName, PassWord);

                        var MeterDataList = new ArrayList();
                        string sql = "";

                      sql = "select top 24 ybdz,xylx,zxlj,zxss,fxlj,fxss,sbsj,fmzt,ybdy,sbdy,xhqz,sbdz,txsj from v_rp_meter_sj where ybdz='" + MeterId + "'and DepartmentId like '" +
                                                                                                                                Departmentid + "%' and sbsj between '" + 
                                                                                                                                BeginTime + "' and '" + 
                                                                                                                                EndTime + "' order by sbsj desc";
                       // select top 48  ybdz,xylx,zxlj,zxss,fxlj,fxss,sbsj,fmzt,ybdy,sbdy,xhqz,sbdz from[WaterMeter].[dbo].[v_rp_meter_ls] where ybdz = '62992108208036'  and DepartmentId like '005014003001001%' and sbsj between '2021-10-12 08:00:00.000' and '2021-10-14 07:00:00.000' order by sbsj desc
                        System.Data.DataTable Meter_Data = WebSdkCore.select(sql);

                        string ybdz = "";
                        string xylx = "";
                        string zxlj = "";
                        string zxss = "";
                        string fxlj = "";
                        string fxss = "";
                        string sbsj = "";
                        string fmzt = "";
                        string meter_fm = "";
                        string ybdy = "";
                        string sbdy = "";
                        string meter_dy = "";
                        string xhqd = "";
                        string sbdz = "";

                        if (Meter_Data.Rows.Count > 0)
                        {
                            int j;
                            if (Meter_Data.Rows.Count > 100)
                            {
                                j = 300;
                            }
                            else
                            {
                                j = Meter_Data.Rows.Count;
                            }

                            for (int i = 0; i < j; i++)
                            {
                                ybdz = Meter_Data.Rows[i]["ybdz"].ToString();
                                xylx = Meter_Data.Rows[i]["xylx"].ToString();
                                zxlj = Meter_Data.Rows[i]["zxlj"].ToString();

                                if (xylx == "0" ||
                                    xylx == "1" ||
                                    xylx == "2" ||
                                    xylx == "3" ||
                                    xylx == "4" ||
                                    xylx == "5" ||
                                    xylx == "6" ||
                                    xylx == "7" ||
                                    xylx == "8" ||
                                    xylx == "9" ||
                                    xylx == "10")
                                {
                                    zxss = "";
                                    fxlj = "";
                                    fxss = "";
                                }
                                else
                                {
                                    zxss = Meter_Data.Rows[i]["zxss"].ToString();
                                    fxlj = Meter_Data.Rows[i]["fxlj"].ToString();
                                    fxss = Meter_Data.Rows[i]["fxss"].ToString();
                                }

                                sbsj= Meter_Data.Rows[i]["txsj"].ToString();
                                fmzt = Meter_Data.Rows[i]["fmzt"].ToString();
                                if (fmzt == "阀开" || fmzt == "Open")
                                {
                                    meter_fm = "1";
                                }
                                else if (fmzt == "阀关" || fmzt == "Close")
                                {
                                    meter_fm = "0";
                                }
                                else
                                {
                                    meter_fm = "2";
                                }

                                ybdy = Meter_Data.Rows[i]["ybdy"].ToString();
                                if (ybdy == "0")
                                {
                                    sbdy = Meter_Data.Rows[i]["sbdy"].ToString();
                                    if (sbdy == "0")
                                    {
                                        sbdy = "";
                                    }
                                    else
                                    {
                                        meter_dy = sbdy;
                                    }
                                }
                                else
                                {
                                    meter_dy = ybdy;
                                }

                                xhqd = Meter_Data.Rows[i]["xhqz"].ToString();
                                sbdz = Meter_Data.Rows[i]["sbdz"].ToString();
                                MeterDataList.Add(new
                                {
                                    MeterId = ybdz,

                                    PositiveCumulativeFlow = zxlj,
                                    DeviceAddress=sbdz,
                                    PositiveInstantaneousFlow = zxss,
                                    AntiCumulativeFlow = fxlj,
                                    AntiInstantaneousFlow = fxss,
                                    WholePointData = sbsj,
                                    ValveStatus = meter_fm,
                                    MeterVoltage = meter_dy,
                                    SignalIntensity = xhqd,
                                }
                                );
                            };
                            var json_result = new
                            {
                                status = "success",
                                MeterDataList = MeterDataList,
                                message = "Newest " + j + " data",
                            };
                            str_result = WebSdkCore.ToJSON(json_result);
                        }
                        else
                        {
                            var json_result = new
                            {
                                status = "success",
                                message = "No data",
                            };
                            str_result = WebSdkCore.ToJSON(json_result);
                        }
                    }
                    else
                    {
                        var json_result = new
                        {
                            status = "error",
                            message = "Cycle too long",
                        };
                        str_result = WebSdkCore.ToJSON(json_result);
                    }
                }
                else
                {
                    var json_result = new
                    {
                        status = "error",
                        message = "Missing parameter",
                    };
                    str_result = WebSdkCore.ToJSON(json_result);
                }
            }
            else
            {
                var json_result = new
                {
                    status = "error",
                    message = "Missing parameter",
                };
                str_result = WebSdkCore.ToJSON(json_result);
            }
            context.Response.Write(str_result);
        }

        private int DateDiff(string dateStart,string dateEnd)
        {
            DateTime start = Convert.ToDateTime(dateStart);
            DateTime end = Convert.ToDateTime(dateEnd);
            TimeSpan sp = end.Subtract(start);
            return sp.Days;
        } 

        public static bool SelectIn(string UserName, string PassWord, string MeterId, string BeginTime, string EndTime)
        {
            bool result;
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord) || string.IsNullOrEmpty(MeterId) || string.IsNullOrEmpty(BeginTime) || string.IsNullOrEmpty(EndTime))
            {
                result = false;
            }
            else
            {
                result = true;
            }
            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}